<?php
include_once("includes/global.php");
include_once("includes/smarty_config.php");
include_once("config/reg_config.php");
if($reg_config)
{
	$config = array_merge($config,$reg_config);
}
if($buid)
{	//已经登录
	msg('main.php');
}
if(is_array($stop_reg))
{
	stop_ip($stop_reg);
	unset($stop_reg);
}
//----------------------------------------------------
if(!empty($_POST['user']))
{
	if($config['closetype']==2)
	{	//关闭注册
		die('access dined!');
	}
	if($config['user_reg_verf'])
	{	//验证码不对
		if(trim($_POST['ckyzwt'])!=trim($_SESSION['YZWT']))
			 die("Verification question error...");
	}

	if(!empty($_POST['sms_code'])){
		if(trim($_POST['sms_code'])!=trim($_SESSION['sms_code'])){
			die("验证码不正确...");
		}
	}

	
	$ip = getip();
	if($config['regctrl']>0)
	{
		$sql = "select * from ".MEMBER." where ip='$ip' and DATE_ADD( NOW() ,INTERVAL -".$config['regctrl']." HOUR ) - regtime < 0";
		$db -> query($sql);
		$num = $db -> num_rows();
		if($num > 0)
		{
			die("Your IP has been registered...");
		}
	}
	if($config['regfloodctrl'] > 0)
	{
		$sql = "select * from ".MEMBER." where ip='$ip' and to_days(regtime) = to_days(now()) ";
		$db -> query($sql);
		$num = $db -> num_rows();
		if($num >= $config['regfloodctrl'])
		{
			die("Your IP has been registered...");
		}	
	}
	
	if($config['ipregctrltime']>0&&$config['ipregctrl'])
	{
		$ipregctrl = explode("\r\n",$config['ipregctrl']);
		$ipregctrl = implode("','",$ipregctrl);
		$sql = "select * from ".MEMBER." where ip in ('$ipregctrl') and DATE_ADD( NOW() ,INTERVAL -".$config['ipregctrltime']." HOUR ) - regtime < 0";
		$db -> query($sql);
		$num = $db -> num_rows();
		if($num > 0)
		{
			die("Your IP has been registered...");
		}
	}
	$user = trim($_POST['user']);
	$pass = trim($_POST['password']);
	$time = time();
	if(valid_mobile($user))
	{
		$_POST["mobile"] = $mobile = $user;
		$_POST["user"] = $user = $mobile;
		if(!is_repeat($user))
		{
			$_POST["user"] = $user = $user.substr(md5($time),-5);
		}
	}
	if(valid_email($user))
	{
		$_POST["email"] = $email = $user;
		//$user = explode("@",$email);
		//$_POST["user"] = $user = $user[0];
		$_POST["user"] = $user ;
		if(!is_repeat($user))
		{
			$_POST["user"] = $user = $user.substr(md5($time),-5);
		}
	}
	if($config['openbbs']==2)
	{	//关联UCHENTER

		if($uid>0)
		{
			doreg($uid);
		}
	}
	else
		doreg();
}
function is_repeat($str)
{
	global $db;
	$sql = "select * from ".MEMBER." where user = '$str'";
	$db -> query($sql);
	$num = $db->num_rows();
	return $num > 0 ? false : true;
}
function valid_mobile($str)//手机号码正则表达试
{                 
 	return ( ! preg_match("/^13[0-9]{1}[0-9]{8}$|14[57]{1}[0-9]{8}$|15[0-9]{1}[0-9]{8}$|18[0-9]{1}[0-9]{8}$/",$str))?FALSE:TRUE; 
}

function valid_email($str)
{
	return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
}

function doreg($guid=NULL)
{
	global $db,$config,$ip;
	$user = $_POST['user'];
	$pass = $_POST['password'];
	$email = $_POST['email'];
	$mobile = valid_mobile($_POST['user']) ? $_POST['user'] : $_POST['mobile'];
	$email_verify = $email&&$config['user_reg']==2 ? "1":"0";
	$mobile_verify = $mobile&&$config['user_reg']==3 ? "1":"0";
	
	$ip = getip();
	$ip = empty($ip)?NULL:$ip;
	$lastLoginTime = time();
	$regtime = date("Y-m-d H:i:s");
	$user_reg = "2";


	
	$db=new dba($config['dbhost'],$config['dbuser'],$config['dbpass'],$config['dbname'],$config['dbport']);
	
	$sql="select * from ".MEMBER." where user = '$user'";
    $db->query($sql);
    if($db->num_rows())
		die("User name is have");

	$sql="insert into ".MEMBER." (user,password,ip,lastLoginTime,email,mobile,regtime,statu,email_verify,mobile_verify) values ('$user','".md5($pass)."','$ip','$lastLoginTime','$email','$mobile','$regtime','2','$email_verify','$mobile_verify')";

	$re=$db->query($sql);

	$userid=$db->lastid();
	
	if($userid)
	{	
		$sql="INSERT INTO ".MEMBERINFO." (member_id) VALUES ('$userid')";
		$re=$db->query($sql);
		
		if($re)
		{			
			//-------------绑定一键连接
			if(!empty($_POST['connect_id']))
			{
				$sql="update ".USERCOON." set userid='$userid' where id='$_POST[connect_id]'";
				$db->query($sql);
			}
			//---------------设置加密的cookie
			bsetcookie("USERID","$userid\t$user",NULL,"/",$config['baseurl']);
			setcookie("USER",$user,NULL,"/",$config['baseurl']);
			//header("Location: main.php?m=member&s=admin_member&cg_u_type=1");
			header("Location: main.php");
		}
	 }
	 else
		 die("Can not register...");
}
include_once("config/reg_config.php");
include_once("config/connect_config.php");//connect
$config = array_merge($config,$reg_config);
$config = array_merge($config,$connect_config);
if($config['sina_connect']==1)//sina
{
	define( "WB_AKEY" , $config['sina_app_id'] );
	define( "WB_SKEY" , $config['sina_key'] );
	define( "WB_CALLBACK_URL" , "$config[weburl]/login.php?type=sina" );
	include_once( 'includes/saetv2.ex.class.php' );
	$o = new SaeTOAuthV2( WB_AKEY , WB_SKEY );
	//------------------------------------------
	if($_GET['type']=='sina'&&isset($_REQUEST['code']))
	{
		$keys = array();
		$keys['code'] = $_REQUEST['code'];
		$keys['redirect_uri'] = WB_CALLBACK_URL;
		$token = $o->getAccessToken( 'code', $keys ) ;
		$c = new SaeTClientV2( WB_AKEY , WB_SKEY , $token['access_token'] );
		$uid_get = $c->get_uid();
		$uid = $uid_get['uid'];
		$ar = $c->show_user_by_id( $uid);//IDȡûȻϢ
		//------------
		$sql="select * from ".USERCOON." where type=2 and client_id='$ar[id]'";
		$db->query($sql);
		$cre=$db->fetchRow();
		if(empty($cre['id']))
		{
			$sql="insert into ".USERCOON."
			(nickname,figureurl,gender,type,access_token,client_id)
			values
			('$ar[name]','$ar[profile_image_url]','$ar[gender]',2,'$token[access_token]','$ar[id]')";
			$db->query($sql);
			$cre['id']=$db->lastid();
		}
		if($cre['userid'])
		{//Ѿ󶨣ת¼
			login($cre['userid'],NULL);
			$forward = $post['forward']?$post['forward']:$config["weburl"]."/main.php";
			msg($forward);
		}
		else
		{//а󶨡
			msg("login.php?connect_id=$cre[id]");
		}
	}
	//-------------------------------------------
	$code_url = $o->getAuthorizeURL( WB_CALLBACK_URL );
	$tpl->assign("sina_login_url",$code_url);
}
if(!empty($_GET['code'])&&$config['qq_connect']==1&&$_GET['type']!='sina')//QQ
{
	//-----------------
	$config['return']=$config['weburl'].'/login.php';
	$url="https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&"
			."client_id=$config[qq_app_id]"
			."&client_secret=$config[qq_key]"
			."&code=$_GET[code]"
			."&state=$config[company]"
			."&redirect_uri=$config[return]";
	$takenid=get_url_contents($url);
	//----------------
	$url2="https://graph.qq.com/oauth2.0/me?$takenid";
	$con=get_url_contents($url2);
	$lpos = strpos($con, "(");
	$rpos = strrpos($con, ")");
	$con  = substr($con, $lpos + 1, $rpos - $lpos -1);
	$ar2=json_decode($con,true);
	//----------------
	$url3 = "https://graph.qq.com/user/get_user_info?"
			. $takenid
			. "&oauth_consumer_key=" . $config['qq_app_id']
			. "&openid=" . $ar2["openid"]
			. "&format=json";
	$con=get_url_contents($url3);
	$ar=json_decode($con,true);
	//--------------------------
	$sql="select * from ".USERCOON." where type=1 and openid='$ar2[openid]'";
	$db->query($sql);
	$cre=$db->fetchRow();
	if(empty($cre['id']))
	{
		$sql="insert into ".USERCOON."
		(nickname,figureurl,gender,vip,level,type,access_token,client_id,openid)
		values
		('$ar[nickname]','$ar[figureurl]','$ar[gender]','$ar[vip]','$ar[level]',1,'$takenid','$ar2[client_id]','$ar2[openid]')";
		$db->query($sql);
		$cre['id']=$db->lastid();
	}
	if($cre['userid'])
	{//Ѿ󶨣ת¼
		login($cre['userid'],NULL);
		$forward = $post['forward']?$post['forward']:$config["weburl"]."/main.php";
		msg($forward);
	}
	else
	{//а󶨡
		msg("login.php?connect_id=$cre[id]");
	}

}

include_once("footer.php");	
$tpl->display("register.htm");
?>